﻿
namespace EAI.Config
{
    using System;
    using System.IO;
    using System.Collections.Generic;
    using System.Text;
    using System.Xml.Serialization;

    using EAI.Logging;


    /// <summary>
    /// The abstract class for config file.
    /// </summary>
    public abstract class ConfigBase
    {
        public string Category { get; set; }

        protected string ConfigPath { get; set; }

        protected string BasePath
        {
            get
            {
                return AppDomain.CurrentDomain.SetupInformation.PrivateBinPath != null ?
                    AppDomain.CurrentDomain.SetupInformation.PrivateBinPath : AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            }
        }

        public string FullConfigPath
        {
            get
            {
                return Path.Combine(BasePath, string.IsNullOrEmpty(Category) ? ConfigPath : string.Format(ConfigPath, Category));
            }
        }

        /// <summary>
        /// Gets the config entity base on specify type.
        /// </summary>
        /// <returns>The derived class entity from config base.</returns>
        public ConfigBase GetConfig()
        {
            ConfigBase xmlObj = null;

            try
            {
                if (File.Exists(FullConfigPath))
                {
                    using (StreamReader streamReader = new StreamReader(FullConfigPath))
                    {
                        XmlSerializer xSerializer = new XmlSerializer(this.GetType());
                        xmlObj = xSerializer.Deserialize(streamReader) as ConfigBase;
                    }
                }
            }
            catch (Exception ex)
            {
                Log4NetHelper.GetLogger().Error(ex.Message, ex);
                throw;
            }

            return xmlObj;
        }

        /// <summary>
        /// Saves the config data entity to xml file.
        /// </summary>
        /// <returns>The boolean value to indicates whether saving the entity to xml file successfully.</returns>
        public void PersistentConfig()
        {
            try
            {
                using (StreamWriter streamWriter = new StreamWriter(FullConfigPath, false))
                {
                    XmlSerializer xmlSerializer = new XmlSerializer(this.GetType());
                    xmlSerializer.Serialize(streamWriter, this);
                }
            }
            catch (Exception ex)
            {
                Log4NetHelper.GetLogger().Error(ex.Message, ex);
                throw;
            }
        }
    }
}
